//
//  HomeViewController.m
//  jdd
//
//  Created by Edward Zhang on 12-5-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddHomeViewController.h"
#import "JddViewControllerManager.h"
#import "JddSFHFKeychainUtils.h"
#import "JddGlobal.h"
#import "JddSecurity.h"
#import "JddNavigationBar.h"
@interface JddHomeViewController ()

@end

@implementation JddHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
	}
	return self;
}

- (void)initJddData {
	[JddSecurity storeSystemData];
	[[JddGlobalParameter sharedInstance] load];
	JddGlobal *jdd = [JddGlobal sharedInstance];
	jdd.navigationController = self.navigationController;
	[jdd load];
}

- (void)viewDidLoad {
	[super viewDidLoad];
    //初始化jdd信息
	[self initJddData];
	[self initNaveView];
//	[JddCommonFunction setViewBackgroundWithImageName:@"jdd_default_bg01" AndView:self.view];
    
    //设置导航条
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"首页" style:UIBarButtonItemStylePlain target:self action:@selector(home)];
    //self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"首页" style:UIBarButtonItemStylePlain target:self action:@selector(home)]; //initWithImage:[UIImage imageNamed:@"backMain"] style:UIBarButtonItemStylePlain target:self action:@selector(home)];
//    self.navigationItem.backBarButtonItem = backItem;
    if(IOS7)
    {
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//        backItem.tintColor=[UIColor whiteColor];
    }
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    self.title = APP_NAME;
    /*
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:18.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    label.text = APP_NAME;*/
    
    //获取版本号
	[self getVersion];
    
    
	JddNoticeOperation *operation = [[JddNoticeOperation alloc] init];
	operation.delegate = self;
	[[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
	
	//记录用户信息
	[self sendUserInfo];

    //如果是自动登录 check一下用户名和密码
    if ([JddCommonFunction isLogin])
        [self checkUserAndPassword];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	//隐藏tabbar
	[self setJddTabBarHidden:YES];
	[self addRightSegment];
	//重置viewControolers
	[JddCommonFunction clearViewControllers];
    
	if ([JddCommonFunction isLogin]) {
		barLoginView.hidden = YES;
	}
	else {
		barLoginView.hidden = NO;
	}
	//初始化btn的tag
	[self initBtnTags];
	//获取用户信息
	[self queryUserInfo];
}
//验证用户信息
- (void)sendUserInfo {
	NSString *passWord =  [JddSFHFKeychainUtils getPasswordForUsername:USER_UUID andServiceName:USER_UUID error:nil];
	if (passWord.length == 0)
    {
		JddSendUserUniqueIdentifierOperation *operation = [[JddSendUserUniqueIdentifierOperation alloc] init];
		operation.delegate = self;
		[[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
	}
}

- (void)SendUserUniqueIdentifierOperationResult:(NSData *)result {
	if (result) {
        NSDictionary *d = [result objectFromJSONData];
        NSLog(@"%@", [d objectForKey:@"Data"]);
	}
}

//- (void)home {
//	[[JddViewControllerManager sharedInstance] popToRootViewController];
//}

- (IBAction)listBtnAction:(id)sender {
	UIButton *btn = (UIButton *)sender;
	NSInteger controllerIndex = [self getControllerIndexWithLotteryId:btn.tag];
	[[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:controllerIndex
	                                                        fromController:self
	                                                            withObject:nil
	                                                           withObject2:nil];
}

- (NSInteger)getControllerIndexWithLotteryId:(NSInteger)lotteryId {
	NSInteger controllerIndex = LOTTERY_TYPE_ID_SHUANGSEQIU;
	switch (lotteryId) {
		case LOTTERY_HALL_HOME:
			controllerIndex = CONTROLLER_LOTTERY_HALL;
			break;
            
		case LOTTERY_OPEN_HOME:
			controllerIndex = CONTROLLER_LOTTERY_OPEN;
			break;
            
		case USER_CENTER_HOME:
			controllerIndex = CONTROLLER_USER_CENTER;
			break;
            
		case SETTING_HOME:
			controllerIndex = CONTROLLER_SETTING;
			break;
            
		case SCORE_HOME:
			controllerIndex = CONTROLLER_SCORE;
			break;
            
		case TOGETHER_BUY_HOME:
			controllerIndex = CONTROLLER_TOGETHER_BUY;
			break;
            
            //彩种
		case LOTTERY_TYPE_ID_SHUANGSEQIU:
			controllerIndex = CONTROLLER_PICK_NUM_SHUANGSEQIU;
			break;
            
		case LOTTERY_TYPE_ID_DALETOU:
			controllerIndex = CONTROLLER_PICK_NUM_DALETOU;
			break;
            
		case LOTTERY_TYPE_ID_11S5:
			controllerIndex = CONTROLLER_PICK_NUM_11s5;
			break;
            
		case LOTTERY_TYPE_ID_FOOTBALL:
			controllerIndex = CONTROLLER_PICK_NUM_SPORT;
			break;
            
		case LOTTERY_TYPE_ID_BD:
			controllerIndex = CONTROLLER_PICK_NUM_BD;
			break;
            
		case LOTTERY_TYPE_ID_BASKETBALL:
			controllerIndex = CONTROLLER_PICK_NUM_BASKETBALL;
			break;
            
		case LOTTERY_TYPE_ID_SF:
			controllerIndex = CONTROLLER_PICK_NUM_SFC;
			break;
            
		case LOTTERY_TYPE_ID_RX9:
			controllerIndex = CONTROLLER_PICK_NUM_RX9;
			break;
            
		case LOTTERY_TYPE_ID_FC3D:
			controllerIndex = CONTROLLER_PICK_NUM_FC3D;
			break;
            
		case LOTTERY_TYPE_ID_7LC:
			controllerIndex = CONTROLLER_PICK_NUM_7L;
			break;
            
		case LOTTERY_TYPE_ID_PL3:
			controllerIndex = CONTROLLER_PICK_NUM_P3;
			break;
            
		case LOTTERY_TYPE_ID_PL5:
			controllerIndex = CONTROLLER_PICK_NUM_P5;
			break;
            
		case LOTTERY_TYPE_ID_7XC:
			controllerIndex = CONTROLLER_PICK_NUM_7X;
			break;
            
		case LOTTERY_TYPE_ID_11YDJ:
			controllerIndex = CONTROLLER_PICK_NUM_11YDJ;
			break;
            
		case LOTTERY_TYPE_ID_CQSS:
			controllerIndex = CONTROLLER_PICK_NUM_CQSS;
			break;
	}
	return controllerIndex;
}

//更新用户信息
- (void)queryUserInfo {
	if ([JddCommonFunction isLogin]) {
		JddQueryUserInfoOperation *operation = [[JddQueryUserInfoOperation alloc] init];
		operation.delegate = self;
		[[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
	}
}

- (void)QueryUserInfoOperationResult:(NSData *)result {
	[JddCommonFunction setWaitingViewHidden:YES fromController:self];
	if (result) {
		[JddDataParser parseUserInfoResult:result];
	}
}
//获取版本号
- (void)getVersion {
    //创建更新版本操作
	JddQueryVersionOperation *operation = [[JddQueryVersionOperation alloc] init];
	operation.delegate = self;
	[[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

//-(void)QueryVersionOperationResult:(NSData *)result{
//    if (result) {
//        int versionCode = [[[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleVersion"] intValue];
//        SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
//        @try {
//            NSDictionary *dictResult = [jsonParser objectWithData:result];
//            int code = [[dictResult objectForKey:@"Code"] intValue];
//            if (code == 0) {
//                NSArray *temoArray = [jsonParser objectWithString:[dictResult objectForKey:@"Data"]];
//                NSDictionary *dictResult22 = [temoArray objectAtIndex:0];
//                int newCode = [[dictResult22 objectForKey:@"verCode"] intValue];
//                NSArray* newMessage = [dictResult22 objectForKey:@"Message"];
//                downLoadURL = [dictResult22 objectForKey:@"apkname"];
//                int bupdate = [[dictResult22 objectForKey:@"bupdate"] intValue];
//                
//                NSString *msg = @"有新的版本可供升级，确定升级？";
//                for (NSString *inmsg in newMessage) {
//                    msg = [msg stringByAppendingFormat:@"\n%@",inmsg];
//                }
//                
//                if (versionCode < newCode /*&& bupdate == 1*/) {
//                    if(bupdate == -1){
//                        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"奖多多更新提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"退出", nil];
//                        [alert show];
//                    }else{
//                        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"奖多多" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//                        [alert show];
//                    }
//                }
//            }
//        }
//        @catch (NSException *e) {
//            NSLog(@"NSException:\t%@", e.reason);
//            [JddError sharedInstance].message = e.reason;
//        }
//    }
//}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSString * URLString = @"https://itunes.apple.com/cn/app/jiang-duo-duo-cai-piao/id562188850?mt=8";
        if ([downLoadURL length] > 0) {
            URLString = downLoadURL;
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
    }else if (buttonIndex == 1){
        if ([alertView.title isEqualToString:@"奖多多更新提示"]) {
            exit(0);
        }
    }
}

//公告回调方法
- (void)NoticeOperationResult:(NSData *)result
{
    NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    NSLog(@"str = %@",str);
	if (result) {
		NSString *strResult = [JddDataParser parseLoginResult:result];
		if (strResult.length > 0) {
			[self setNoticesShowStyleWithString:strResult];
		}
	} else {
        
    }
}
//设置公告信息
- (void)setNoticesShowStyleWithString:(NSString *)strResult
{
	noticeDict = [strResult objectFromJSONString];
//	noticesCount = noticeDict.count;
	page = 0;
	[self setNoticeBtnTitle];
	[self.noticeBtn addTarget:self action:@selector(noticeDetail:) forControlEvents:UIControlEventTouchUpInside];
    
	//定时器
	timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(runTimeNotices) userInfo:nil repeats:YES];
}
//公告滚动效果
- (void)runTimeNotices
{
	CATransition *animation = [CATransition animation];
	[self setNoticeBtnTitle];
	page += 1;
	if (page == 4) {
		page = 0;
	}
	animation.delegate = self;
	animation.duration = 1.0f; //动画时长
	animation.timingFunction = UIViewAnimationCurveEaseInOut;
	animation.fillMode = kCAFillModeForwards;
	animation.type = @"cube"; //过度效果
	animation.subtype = @"fromTop"; //过渡方向
	animation.removedOnCompletion = NO;
    
	[self.noticeBtn.layer addAnimation:animation forKey:@"animation"];
}
//设置首页滚动公告标题
- (void)setNoticeBtnTitle {

    NSArray *arr = [noticeDict objectForKey:@"item"];
    
	[self.noticeBtn setTitle:[arr[page] objectForKey:@"Title"] forState:UIControlStateNormal];
	self.noticeBtn.tag = page;
}

- (IBAction)noticeDetail:(id)sender {
    
    NSArray *noticeArr = [noticeDict objectForKey:@"item"];
	NSString *noticeId = [[noticeArr objectAtIndex:self.noticeBtn.tag] objectForKey:@"ID"];
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_NOTICE_DETAIL
	                                                        fromController:self
	                                                            withObject:noticeId
	                                                           withObject2:nil];
}

- (void)initNaveView {
	UIImage *naveViewBackGround = LOADIMAGE(@"jdd_default_bg01");
	self.navView.backgroundColor = [UIColor colorWithPatternImage:naveViewBackGround];
    
	if (iPhone5) {
		CGRect navViewFrame = self.navView.frame;
		navViewFrame.origin.y += 50;
		self.navView.frame = navViewFrame;
	}
}

//初始化按钮tag
- (void)initBtnTags {
	self.lotteryHallBtn.tag = LOTTERY_HALL_HOME;
	self.lotteryOpenBtn.tag = LOTTERY_OPEN_HOME;
	self.userCenterBtn.tag = USER_CENTER_HOME;
	self.settingBtn.tag = SETTING_HOME;
	self.scoreBtn.tag = SCORE_HOME;
	self.toghterBuyBtn.tag = TOGETHER_BUY_HOME;
    
	NSMutableDictionary *dictionary = [JddCommonFunction updateBuyLotteryListWithLotteryId:0];
	//取得彩种ID
	int lotteryId1 = [[dictionary objectForKey:@"btn1"] intValue];
	int lotteryId2 = [[dictionary objectForKey:@"btn2"] intValue];
	int lotteryId3 = [[dictionary objectForKey:@"btn3"] intValue];
	int lotteryId4 = [[dictionary objectForKey:@"btn4"] intValue];
	//设置tag
	self.btn1.tag = lotteryId1;
	self.btn2.tag = lotteryId2;
	self.btn3.tag = lotteryId3;
	self.btn4.tag = lotteryId4;
	//设置对应的图片
	[self.btn1 setBackgroundImage:LOADIMAGE([JddCommonFunction getImgByLotteryId:lotteryId1]) forState:UIControlStateNormal];
	[self.btn2 setBackgroundImage:LOADIMAGE([JddCommonFunction getImgByLotteryId:lotteryId2]) forState:UIControlStateNormal];
	[self.btn3 setBackgroundImage:LOADIMAGE([JddCommonFunction getImgByLotteryId:lotteryId3]) forState:UIControlStateNormal];
	[self.btn4 setBackgroundImage:LOADIMAGE([JddCommonFunction getImgByLotteryId:lotteryId4]) forState:UIControlStateNormal];
	//设置label显示
	self.lbl1.text = [JddCommonFunction getNameByLotteryId:lotteryId1];
	self.lbl2.text = [JddCommonFunction getNameByLotteryId:lotteryId2];
	self.lbl3.text = [JddCommonFunction getNameByLotteryId:lotteryId3];
	self.lbl4.text = [JddCommonFunction getNameByLotteryId:lotteryId4];
}

//添加登录注册
- (void)addRightSegment {
    //**********************
//    self.navigationController.navigationBarHidden = YES;
//    
//    UIView *navBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
//    navBarView.backgroundColor = [UIColor redColor];
//    NSArray *titleArr = [NSArray arrayWithObjects:@"注册",@"登录", nil];
//    for (int i=0;i<2;i++) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//        [button setTitle:[titleArr objectAtIndex:i] forState:UIControlStateNormal];
//        button.tag = i;
//        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        button.frame = CGRectMake(240+i*40, 10, 38, 24);
//        [button setBackgroundImage:[UIImage imageNamed:@"alfBtn.png"] forState:UIControlStateNormal];
//        button.layer.cornerRadius = 4.0;
//        button.layer.masksToBounds = YES;
//        [button addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
//        [navBarView addSubview:button];
//    }
//    [self.view addSubview:navBarView];
    
    
    barLoginView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 75, 30)];
    barLoginView.backgroundColor = [UIColor clearColor];
    UIButton *regButton = [UIButton buttonWithType:UIButtonTypeCustom];
    regButton.tag = 0;
    [regButton setTitle:@"注册" forState:UIControlStateNormal];
    regButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [regButton setBackgroundImage:[UIImage imageNamed:@"alfBtn"] forState:UIControlStateNormal];
    [regButton addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
    regButton.frame = CGRectMake(3, 3, 38,24);
    regButton.layer.cornerRadius = 4.0;
    regButton.layer.masksToBounds = YES;
    [barLoginView addSubview:regButton];
    
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.tag = 1;
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"alfBtn"] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
    loginButton.frame = CGRectMake(43, 3, 38,24);
    loginButton.layer.cornerRadius = 4.0;
    loginButton.layer.masksToBounds = YES;
    [barLoginView addSubview:loginButton];

    UIBarButtonItem *barRegbutton = [[UIBarButtonItem alloc] initWithCustomView:barLoginView];
    self.navigationItem.rightBarButtonItem = barRegbutton;
    
}

- (void)segmentAction:(id)sender {
	UIButton *us = (UIButton *)sender;
	if (us.tag == 0) {
		[[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_REGISTER
		                                                        fromController:self
		                                                            withObject:nil
		                                                           withObject2:nil];
	}
	else {
		[[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
		                                                        fromController:self
		                                                            withObject:nil
		                                                           withObject2:nil];
	}
}

//---显示主页时，进行一次用户名和密码的检查，此功能目的，修改了密码，还能登录
-(void) checkUserAndPassword
{
    JddLogonOperation *operation = [[JddLogonOperation alloc] init];
    operation.delegate = self;
    operation.userName     = [JddUserProfile sharedInstance].name;
    operation.userPassword = [JddUserProfile sharedInstance].password;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

//
- (void)LogonOperationResult:(NSData *)result
{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result)
    {
        NSString *uId = [JddDataParser parseLoginResult:result];
        if (uId.length == 0)
        {
            NSString *hintString = [NSString stringWithFormat:@"%@\n(可能密码被修改,如不是本人操作，请联系客服。)",[JddError sharedInstance].message];
            [JddCommonFunction messageBoxWithMessage:hintString];
            [JddUserProfile clearMessage];
            [self.navigationController popToRootViewControllerAnimated:YES];
            barLoginView.hidden = NO;
        }
        else
        {
        }
    }
}


@end
